/*
 *
 *  * Copyright 2019 Zhongan.io All right reserved. This software is the
 *  * confidential and proprietary information of Zhongan.io ("Confidential
 *  * Information"). You shall not disclose such Confidential Information and shall
 *  * use it only in accordance with the terms of the license agreement you entered
 *  * into with Zhongan.io.
 *
 */

package com.sample.common.common.util;

/**
 * 16进制工具类
 *
 * @author za-zhubin002
 * Created in 17:11 2019/5/15
 */
public class HexUtils {

    private static final String HEX_CHARS = "0123456789abcdef";

    /**
     * 将byte数组转化为对应16进制字符串
     *
     * @param b byte数组
     * @return 6进制字符串
     */
    public static String toHexString(byte[] b) {
        StringBuilder sb = new StringBuilder();
        for (byte aB : b) {
            sb.append(HexUtils.HEX_CHARS.charAt(aB >>> 4 & 0x0F));
            sb.append(HexUtils.HEX_CHARS.charAt(aB & 0x0F));
        }
        return sb.toString();
    }

    /**
     * 将16进制字符串转化为byte数组
     *
     * @param s 16进制字符串
     * @return byte数组
     */
    public static byte[] toByteArray(String s) {
        byte[] buf = new byte[s.length() / 2];
        int j = 0;
        for (int i = 0; i < buf.length; i++) {
            buf[i] = (byte) ((Character.digit(s.charAt(j++), 16) << 4) | Character
                    .digit(s.charAt(j++), 16));
        }
        return buf;
    }

}
